package session;

import java.sql.Time;
import java.util.Date;
import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.Query;

import entity.Appointment;

/**
 * Dao bean klasa za entitet User
 * 
 * @author rigo
 *
 */
@Stateless
@Remote(AppointmentDao.class)
public class AppointmentDaoBean extends GenericDaoBean<Appointment, Integer>  implements AppointmentDao{

	@SuppressWarnings("unchecked")
	@Override
	public List<Appointment> listAllAvailable() {
		try{
			Date current = new Date();
			Query q = em.createQuery("SELECT a FROM Appointment a WHERE a.date>:current AND a.deleted=false ORDER BY a.date ASC, a.from ASC");
			q.setParameter("current", current);
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
		
	}

	@Override
	public Boolean checkAppointment(Date date, Time from, Time to) {
		try{
			Query q = em.createQuery("SELECT a FROM Appointment a " +
					"WHERE a.date=:dat and not(a.from>=:too or a.to<=:fr)  AND a.deleted=false");
			q.setParameter("dat", date);
			q.setParameter("fr", from);
			q.setParameter("too", to);
			if(q.getResultList().size()>0)
				return false;
			else
				return true;
		}catch(Exception e){
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Appointment> listAllPast() {
		try{
			Date current = new Date();
			Query q = em.createQuery("SELECT a FROM Appointment a WHERE a.date<:current AND a.deleted=false ORDER BY a.date DESC, a.from DESC");
			q.setParameter("current", current);
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Appointment> listAllAdminable() {
		try{
			Date current = new Date();
			Query q = em.createQuery("SELECT a FROM Appointment a WHERE a.date<:current AND a.expired=false AND a.deleted=false ORDER BY a.date ASC");
			q.setParameter("current", current);
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
	}

}
